package cn.larry.tools.des;

import cn.larry.tools.cons.Constants;
import cn.larry.tools.string.StringTool;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * @version 1.0
 * @Author llin
 * @Date 2020/5/28 11:33
 */
public class DesTool implements Des {


    /**
     * 加密
     *
     * @param strKey      密钥
     * @param str         明文
     * @param charsetName 编码格式（default：UTF-8）
     * @return
     */
    @Override
    public String getEncrypt(String strKey, String str, String charsetName) {
        if (StringTool.isBlank(charsetName))
            charsetName = Constants.CODING_NAME_UTF8_UPCASE;

        if (StringTool.isBlank(str) || StringTool.isBlank(strKey))
            return null;
        byte[] byteMi = null;
        byte[] byteMing = null;
        String strMi = "";
        try {
            byteMing = str.getBytes(charsetName);
            byteMi = this.getEncryptIsNotBase64(getKey(strKey), byteMing);
            strMi = new String(Base64.encode(byteMi));
        } catch (Exception e) {
            throw new RuntimeException(
                    "[getEncString]Error initializing. Cause: " + e);
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMi;
    }

    /**
     * 解密
     *
     * @param strKey      密钥
     * @param str         密文
     * @param charsetName 编码格式（default：UTF-8）
     * @return
     */
    @Override
    public String getDecrypt(String strKey, String str, String charsetName) {
        if (StringTool.isBlank(charsetName))
            charsetName = Constants.CODING_NAME_UTF8_UPCASE;

        byte[] byteMing = null;
        byte[] byteMi = null;
        String strMing = "";
        try {
            byteMi = Base64.decode(str);
            byteMing = this.getDecryptIsNotBase64(getKey(strKey), byteMi);
            strMing = new String(byteMing, charsetName);
        } catch (Exception e) {
            throw new RuntimeException(
                    "[getDecrypt]Error initializing. Cause: " + e);
        } finally {
            byteMing = null;
            byteMi = null;
        }
        return strMing;
    }

    /**
     * 加密
     *
     * @param key     密钥
     * @param strByte 明文
     * @return
     */
    @Override
    public byte[] getEncrypt(Key key, byte[] strByte) {
        return getEncryptIsNotBase64(key, strByte);
    }

    /**
     * 解密
     *
     * @param key     密钥
     * @param strByte 密文
     * @return
     */
    @Override
    public byte[] getDecrypt(Key key, byte[] strByte) {
        return getDecryptIsNotBase64(key, strByte);
    }

    /**
     * @param strKey
     * @return
     */
    @Override
    public Key getKey(String strKey) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            DESKeySpec keySpec = new DESKeySpec(strKey.getBytes());
            keyFactory.generateSecret(keySpec);
            return keyFactory.generateSecret(keySpec);
        } catch (Exception e) {
            throw new RuntimeException(
                    "[getKey]Error initializing. Cause: " + e);
        }
    }

    @Override
    public byte[] getEncryptIsNotBase64(Key key, byte[] strByte) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byteFina = cipher.doFinal(strByte);
        } catch (Exception e) {
            throw new RuntimeException(
                    "[getEncrypt]Error initializing. Cause: " + e);
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    @Override
    public byte[] getDecryptIsNotBase64(Key key, byte[] strByte) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byteFina = cipher.doFinal(strByte);
        } catch (Exception e) {
            throw new RuntimeException(
                    "[getDecryptIsNotBase64]Error initializing. Cause: " + e);
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    @Override
    public byte[] getBase64Decode(String str) {
        return Base64.decode(str);
    }

    @Override
    public String getBase64Encode(byte[] bytes) {
        return new String(Base64.encode(bytes));
    }
}
